package com.ggp.internetcall;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class Loader extends Activity {

	// Data storage to avoid losing data when screen orientation is changed
	private static String mBalance = "";
	private static String mBalance2 = "";
	private static String mContactName = "";
	private static String mReceiverNumber = "";
	private static boolean mForceBalanceUpdate = false;
	private static boolean mForcePreferencesActivity = false;
	
	private String mLicense = "";
	private Handler mHandler;
	private SharedPreferences mPreferences;
	
	private static final int DIALOG_LICENSE = 1;
	private static final int DIALOG_CHECK_PREFERENCES = 2;	
	private static final int DIALOG_RATINGS_MESSAGE = 3;
	
	private static final String ASSET_LICENSE = "LICENSE";
	private static final String HANDLER_DIALOG_ID = "dialog_id";
	private static final String HANDLER_TOAST_MESSAGE = "show_toast";
	
	protected static void setBalance(String balance, String balance2) {
		mBalance = balance;
		mBalance2 = balance2;
	}
	
	protected static String[] getBalance() {
		return new String[] { mBalance, mBalance2 };
	}
	
	protected static void setContactName(String contactName) {
		mContactName = contactName;
	}
	
	protected static String getContactName() {
		return mContactName;
	}
	
	protected static void setReceiverNumber(String receiverNumber) {
		mReceiverNumber = receiverNumber;
	}
	
	protected static String getReceiverNumber() {
		return mReceiverNumber;
	}
	
	protected static boolean getForceBalanceUpdate() {
		return mForceBalanceUpdate;
	}
	
	protected static void setForceBalanceUpdate(boolean forceBalanceUpdate) {
		mForceBalanceUpdate = forceBalanceUpdate;
	}
	
	protected static boolean getForcePreferencesActivity() {
		return mForcePreferencesActivity;
	}
	
	protected static void setForcePreferencesActivity(boolean forcePreferencesActivity) {
		mForcePreferencesActivity = forcePreferencesActivity;
	}

	private void showLicense() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				mLicense = readLicense();
				Looper.prepare();
				Bundle messageData = new Bundle();
				messageData.putInt(HANDLER_DIALOG_ID, DIALOG_LICENSE);
				Message message = mHandler.obtainMessage();
				message.setData(messageData);
				while (mLicense.length() == 0) { }
				mHandler.sendMessage(message);
				Looper.loop();
			}
		}).start();
	}
	
	private String readLicense() {
		StringBuffer license = new StringBuffer("");
		try {
			InputStream licenseIs = this.getAssets().open(ASSET_LICENSE);
			BufferedReader reader = new BufferedReader(new InputStreamReader(licenseIs));
			String line;
			while ((line = reader.readLine()) != null) {
				license = license.append(line).append("\n");
			}
		} catch (IOException e) { }
		return license.toString();
	}	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Reset stored data
		mBalance = "";
		mBalance2 = "";
		mContactName = "";
		mReceiverNumber = "";
		
		// Create notifications handler
    	mHandler = new Handler() {
        	public void handleMessage(Message message) {
        		if (message.getData().containsKey(HANDLER_DIALOG_ID)) {
        			showDialog(message.getData().getInt(HANDLER_DIALOG_ID));
        		}
        		if (message.getData().containsKey(HANDLER_TOAST_MESSAGE)) {
        			Toast.makeText(getApplicationContext(), message.getData().getString(HANDLER_TOAST_MESSAGE), Toast.LENGTH_SHORT).show();
        		}
        	}
    	};		
		
    	// Start checking process (license, personal request & preferences)
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        Boolean checkBalance = mPreferences.getBoolean(Preferences.KEY_CHECK_BALANCE_STARTUP, false);
        mForceBalanceUpdate = checkBalance.booleanValue();
        
        checkEula();
   	}

	private void checkEula() {
        Boolean eulaAccepted = mPreferences.getBoolean(Preferences.KEY_EULA_ACCEPTED, false);
        if (!eulaAccepted.booleanValue()) {
        	showLicense();
        } else {
        	checkRatingsMessage();
        }
	}
	
    private void checkRatingsMessage() {
        Boolean ratingsMsgShown = mPreferences.getBoolean(Preferences.KEY_RATINGS_MSG_SHOWN, false);
        if (!ratingsMsgShown.booleanValue()) {
        	showDialog(DIALOG_RATINGS_MESSAGE);
        } else {
        	goMainScreen();
        }
    }
	    
    private void goMainScreen() {
		Intent intent = new Intent(getApplicationContext(), Main.class);
		startActivity(intent);
		finish();    	
    }
    
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LICENSE:
			return new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_info)
				.setTitle(R.string.license)
				.setMessage(mLicense)
				.setCancelable(false)
				.setPositiveButton(R.string.accept, new Dialog.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mPreferences.edit().putBoolean(Preferences.KEY_EULA_ACCEPTED, true).commit();
						checkRatingsMessage();
						dialog.dismiss();
					}
				})
				.setNegativeButton(R.string.refuse, new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Loader.this.finish();
					}
				})
				.create();
		case DIALOG_RATINGS_MESSAGE:
			return new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_info)
			.setTitle(R.string.personal_request)
			.setMessage(R.string.ratings_request)
			.setCancelable(false)
			.setNeutralButton(R.string.accept, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mPreferences.edit().putBoolean(Preferences.KEY_RATINGS_MSG_SHOWN, true).commit();					
					goMainScreen();
					dialog.dismiss();
				}
			}).create();
		case DIALOG_CHECK_PREFERENCES:
			return new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle(R.string.warning)
				.setMessage(R.string.check_preferences)
				.setNeutralButton(R.string.go_preferences, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mForcePreferencesActivity = true;
						goMainScreen();
					}
				}).create();
			
		}
		return null;
	}

}
